package com.angel.service;

import com.angel.bean.Employee;
import com.angel.bean.InMessage;
import com.angel.socket.OutMessage;
import com.angel.socket.WebSocketUrl;
import com.angel.socket.WebSocketUsers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.Iterator;
import java.util.Map;

@Service
public class WebSocketService {

    @Autowired
    private SimpMessagingTemplate template;
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private InMessageService inMessageService;
    /**
     * 发送消息给指定员工
     *
     * @param msg
     */
    public void sendToEmp(InMessage msg) {
        Iterator iter = WebSocketUsers.eMap.entrySet().iterator();
//        检测消息是否发送成功
        boolean flag = true;
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            Employee emp = (Employee) entry.getValue();
            //如果指定用户存在，这发送给指定用户，如果指定用户不存在，则原路返回
            if (emp.getEmId().equals(msg.getTo())) {

                Employee fromEmp = new Employee();
                fromEmp.setEmId(Integer.valueOf(msg.getFrom()));
                fromEmp = employeeService.findOne(fromEmp);
                OutMessage out = new OutMessage(fromEmp.getEmName(),msg.getContent());
                flag = false;
                template.convertAndSend(WebSocketUrl.P2PPUSHBASEPATH+"/"+msg.getTo()+WebSocketUrl.P2PPUSHPATH,out);
                msg.setTime(new Timestamp(System.currentTimeMillis()));
                inMessageService.insertSelective(msg);
                break;
            }
        }
        //消息未发送成功
        if (flag) {
            OutMessage out = new OutMessage("系统提示：","该用户已经下线");
            template.convertAndSendToUser(msg.getFrom().toString(), WebSocketUrl.P2PPUSHPATH, out);
        }
    }

}
